/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.alibaba.excel.EasyExcel;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Product;
import me.zhengjie.modules.system.domain.PurchaseRequest;
import me.zhengjie.modules.system.domain.PurchaseRequestDetail;
import me.zhengjie.modules.system.excel.listener.ProductListener;
import me.zhengjie.modules.system.excel.vo.ProductVo;
import me.zhengjie.modules.system.excel.vo.PurchaseRequestDetailVo;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.ProductRepository;
import me.zhengjie.modules.system.service.ProductService;
import me.zhengjie.modules.system.service.dto.ProductDto;
import me.zhengjie.modules.system.service.dto.ProductQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.ProductMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;
import org.springframework.web.multipart.MultipartFile;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author 李忠臻
* @date 2024-02-28
**/
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService {

    private final ProductRepository productRepository;
    private final ProductMapper productMapper;

    private final ProductListener productListener;

    @Override
    public PageResult<ProductDto> queryAll(ProductQueryCriteria criteria, Pageable pageable){
        Page<Product> page = productRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(productMapper::toDto));
    }

    @Override
    public List<ProductDto> queryAll(ProductQueryCriteria criteria){
        return productMapper.toDto(productRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public ProductDto findById(Long id) {
        Product product = productRepository.findById(id).orElseGet(Product::new);
        ValidationUtil.isNull(product.getId(),"Product","id",id);
        return productMapper.toDto(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Product resources) {
        productRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Product resources) {
        Product product = productRepository.findById(resources.getId()).orElseGet(Product::new);
        ValidationUtil.isNull( product.getId(),"Product","id",resources.getId());
        product.copy(resources);
        productRepository.save(product);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            productRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ProductDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ProductDto product : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("分类", product.getType());
            map.put("条码", product.getBarCode());
            map.put("品牌", product.getBrand());
            map.put("产品编码", product.getProductCode());
            map.put("产品名称", product.getProductName());
            map.put("单位", product.getUnit());
            map.put("重量", product.getWeight());
            map.put("出厂价", product.getFactoryPrice());
            map.put("采购价", product.getPurchasePrice());
            map.put("最小库存", product.getMinStock());
            map.put("最大库存", product.getMaxStock());
            map.put("实际库存", product.getStock());
            map.put("创建者", product.getCreateBy());
            map.put("更新者", product.getUpdateBy());
            map.put("创建日期", product.getCreateTime());
            map.put("更新时间", product.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String upload(String name, MultipartFile file) {
        String result = new String();
        String modelStr = new String();
        try {
            List<ProductVo> productVoList = EasyExcel.read(file.getInputStream(), ProductVo.class, null).sheet().doReadSync();
            result = result + "本次上传" + productVoList.size() + "条数据，";
            int updateNum = 0;
            for (ProductVo productVo : productVoList) {
                Product p = new Product();
                BeanUtils.copyProperties(productVo, p);
                Product l = productRepository.findByProductCode(productVo.getProductCode());
                if (l !=null) {
                    updateNum++;
                    modelStr = modelStr + productVo.getProductCode() + "，";
                    p.setId(l.getId());
                }
                productRepository.save(p);
            }
            if (updateNum > 0) {
                result = result + "其中更新" + updateNum + "条数据，涉及的型号为：" + modelStr;
            }


        } catch (IOException e) {
            e.printStackTrace();
            throw new BadRequestException(e.getMessage());
        }
        return result;
    }
}